import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, Alert, TouchableOpacity, ScrollView, Vibration } from 'react-native';
import { Icon, List, ListItem, Button, SearchBar, FormLabel, FormInput, CheckBox } from 'react-native-elements';
import { primaryColor, executor, toast } from './utils';
import NavNext from './widgets/NavNext';
import update from 'immutability-helper';

const styles = StyleSheet.create({
  icon: {
    marginRight: 16
  },
  fill: {
    flex: 1,
    backgroundColor: 'white'
  },
  button: {
    marginTop: 16
  }
});

class StoreEditButton extends Component {
  state = {}
  onSubmit = () => {
    const { id, title, type } = this.props.navigation.state.params;
    if (!title) return toast('Please enter a name');
    if (!type) return toast('Please select store type');

    executor(id?this.props.updateStore:this.props.deleteStore, this.props.navigation.state.params)
      .then(({res}) => {
        if (res) {
          this.props.navigation.goBack();
        }
        this.setState({processing: false});
      });
    this.setState({processing: true});
  }
  render() {
    const navigation = this.props.navigation;

    return (
      <NavNext title={navigation.state.params.id?'Update':'Create'} processing={this.state.processing}
        onPress={this.onSubmit}/>
    );
  }
}

const StoreEditButtonContainer = compose(
  graphql(gql`
    mutation createStore($title:String!,$type:String!) {
      createStore(title:$title,type:$type) {
        id
        title
        type
      }
    }
  `, {
    name: 'createStore',
    props: ({createStore}) => {
      return {
        createStore: (variables) => createStore({
          variables,
          updateQueries: {
            StoreList: (prev, { mutationResult }) => {
              const newItem = mutationResult.data.createStore;

              return update(prev, {
                stores: {
                  $unshift: newItem,
                }
              });
            }
          }
        })
      };
    }
  }),
  graphql(gql`
    mutation updateStore($storeId:String!,$title:String,$type:String) {
      updateStore(storeId:$storeId,title:$title,type:$type) {
        id
        title
        type
      }
    }
  `, {
    name: 'updateStore',
    props: ({ownProps:{navigation:{state:{params}}}, updateStore}) => {
      return {
        updateStore: (variables) => updateStore({
          variables:{storeId:params.id, ...variables}
        })
      };
    }
  })
)(StoreEditButton);

class StoreEditPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: navigation.state.params.id?`Edit Store '${navigation.state.params.title}'`:`Create New Store`,
      headerRight: <StoreEditButtonContainer navigation={navigation}/>
    };
  }
  onTitleChange = (title) => this.props.navigation.setParams({title})
  onHanger = () => this.props.navigation.setParams({type:'Hanger'})
  onBag = () => this.props.navigation.setParams({type:'Bag'})
  onDeleteStore = () => {
    const params = this.props.navigation.state.params;

    Alert.alert(
      `Delete sore will remove all items out off this store, are you sure you want to delete ${params.title}?`,
      null,
      [
        {text: 'Cancel'},
        {text: 'Delete', onPress: () => {
          executor(this.props.deleteStore)
            .then(({res}) => {
              if (res) {
                toast('Deleted');
                this.props.navigation.goBack();
              }
            });
          toast('Deleting...');
        }},
      ],
      { cancelable: true }
    );
  }
  render() {
    const { id, title, type } = this.props.navigation.state.params;

    return (
      <View style={styles.fill}>
        <FormLabel>Store Name</FormLabel>
        <FormInput defaultValue={title} onChangeText={this.onTitleChange}/>
        <FormLabel>Store Type</FormLabel>
        <CheckBox title='Hanger' checkedIcon='dot-circle-o' uncheckedIcon='circle-o' checked={'Hanger'===type}
          onPress={this.onHanger}/>
        <CheckBox title='Bag' checkedIcon='dot-circle-o' uncheckedIcon='circle-o' checked={'Bag'===type}
          onPress={this.onBag}/>
        {id&&<Button containerViewStyle={styles.button} title='Delete Store' backgroundColor='red' onPress={this.onDeleteStore}/>}
      </View>
    );
  }
}

export default graphql(gql`
  mutation deleteStore($storeId:String!) {
    deleteStore(storeId:$storeId)
  }
`, {
  name: 'deleteStore',
  props: ({ownProps:{navigation:{state:{params}}}, deleteStore}) => {
    return {
      deleteStore: () => deleteStore({
        variables:{storeId:params.id},
        updateQueries: {
          StoreList: (prev, { mutationResult }) => {
            const deletedId = mutationResult.data.deleteStore;
            const index = prev.stores.findIndex(item => item.id===deletedId);

            if (index >= 0) {
              return update(prev, {
                stores: {
                  $splice: [[index, 1]],
                }
              });
            } else {
              return prev;
            }
          },
        }
      })
    };
  }
})(StoreEditPage);

